<template>
  <view class="order tn-safe-area-inset-bottom">
    <tn-navbar z-index="1" index-url="/pages/index" fixed :bottom-shadow="false">买方订单</tn-navbar>
    <tn-sticky :custom-navbar-height="customNavbar.height">
      <view class="order-tabs">
        <tn-tabs :data="tabsData" :current="currentTab" @change="tabClick"></tn-tabs>
      </view>
    </tn-sticky>
    <view class="order-list">
      <view class="order-list-item" v-for="(order, index) in orderList">
        <view class="item-top tn-flex-row">
          <view class="order-sn tn-flex-2"> 订单号：{{ order.orderSn }} </view>
          <view class="order-status tn-flex-1 tn-color-main">
            <view v-if="order.status === 1">
              待付款
            </view>
            <view v-if="order.status === 2">
              待收款确认
            </view>
            <view v-if="order.status === 3 && order.isPickUp == 0">
              待上架
            </view>
            <view v-if="order.status === 4">
              已完成
            </view>
            <view v-if="order.isPickUp == 1">
              已提货
            </view>
          </view>
        </view>
        <view class="item-content tn-flex-row">
          <view class="goods-img tn-flex-2">
            <img :src="order.goodsImgs[0]" />
          </view>
          <view class="goods-info tn-flex-row tn-flex-6">
            <view class="goods-info-name tn-flex-5">
              {{ order.goodsName }}</view>
            <view class="goods-info-other tn-flex-column tn-flex-2">
              <view class="goods-price">￥{{ order.price }}</view>
              <view class="goods-num">x1</view>
            </view>
          </view>
        </view>
        <view class="item-action">
          <!-- 未支付 -->
          <tn-button class="item-button" v-if="order.status === 1" plain border borderColor="tn-border-main"
            color="tn-color-main" @click="cancelOrder">取消</tn-button>
          <tn-button class="item-button" v-if="order.status === 1" plain border borderColor="tn-border-main"
            color="tn-color-main" @click="toUploadProof(order.id)">上传凭证</tn-button>
          <tn-button class="item-button" v-if="order.status === 1" border bgColor="tn-bg-main"
            @click="toPaymentInfo(order.price, order.sellerId)">去支付</tn-button>
          <!-- 待确认收款 -->
          <tn-button class="item-button" v-if="order.status === 2" plain border borderColor="tn-border-main"
            color="tn-color-main" @click="showProofPopup(order.payProof)">查看凭证</tn-button>
          <tn-button class="item-button" v-if="order.status === 2" border borderColor="tn-bg-main"
            @click="toUploadProof(order.id)">重新上传凭证</tn-button>
          <!-- 支付完毕确认收款后 -->
          <tn-button class="item-button" v-if="order.status === 3 && order.isPickUp == 0" borderColor="tn-border-main" color="tn-color-main" plain border @click="handlePickUp(order.id)">提货</tn-button>
          <tn-button class="item-button" v-if="order.status === 3 &&  order.isPickUp == 0" border bgColor="tn-bg-main" @click="toPutSale(order.id)">委托上架</tn-button>
          
        </view>
      </view>

      <tn-empty :show="emptyOrderList" mode="data"></tn-empty>
      <tn-load-more :status="loadingStatus" :load-tips-text="loadMoreTipsText"></tn-load-more>
    </view>
    <tn-popup v-model="payProofPopup" bg-color="transparent" mode="center" width="90%" height="70%">
      <view class="proof-content">
       <img :src="proofImg" />
      </view>
    </tn-popup>
    <tn-modal v-model="confirmModal" :data="confirmModalData" show-cancel @confirm="handleConfirmPickUp"></tn-modal>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { onReachBottom, onLoad } from "@dcloudio/uni-app";
import TnNavbar from "@/tuniao-ui/components/tn-navbar/src/Navbar.vue";
import TnTabs from "@/tuniao-ui/components/tn-tabs/src/Tabs.vue";
import TnLoadMore from "@/tuniao-ui/components/tn-load-more/src/LoadMore.vue";
import TnButton from "@/tuniao-ui/components/tn-button/src/Button.vue";
import TnEmpty from "@/tuniao-ui/components/tn-empty/src/Empty.vue";
import TnSticky from "@/tuniao-ui/components/tn-sticky/src/Sticky.vue";
import TnPopup from "@/tuniao-ui/components/tn-popup/src/Popup.vue";
import TnModal from "@/tuniao-ui/components/tn-modal/src/Modal.vue";
import { navPage } from "@/tuniao-ui/utils";
import { onShow } from "@dcloudio/uni-app";
import { TabData } from "@/tuniao-ui/types";
import { ModalDataType } from "@/tuniao-ui/types";
import { LoadMoreStatus } from "@/tuniao-ui/types/tn-load-more";
import { ResultEnum } from "@/enums/httpEnum";
import { findBuyerOrder, orderPickUp} from "@/api/purchaseDetail";
import { toast } from "@/tuniao-ui/utils/messageUtils";

// 获取自定义顶部导航栏的高度
import useSystemInfo from "@/tuniao-ui/libs/hooks/useSystemInfo";
const { customNavbar } = useSystemInfo()
// 订单接口
interface OrderVO {
  id: number;
  orderSn: string;
  goodsImgs: [];
  goodsName: string;
  price: number;
  goodsNum: number;
  status: number;
  sellerId: number;
  payProof: string;
  isPickUp: number;
}
const orderList = ref<OrderVO[]>([]);
const emptyOrderList = ref(false);
const haveData = ref(true);
// tabs数据
const tabsData = ref<TabData[]>([
  { title: "全部" },
  { title: "待付款" },
  { title: "待收款确认" },
  { title: "待上架" },
  { title: "已完成" },
]);
// 当前操作的订单id
const currentOrderId = ref(0);
//默认选择tab页
const currentTab = ref(0);
const status = ref("all"); //当前选中状态
const loadMoreTipsText = {
  loadmore: "上滑加载更多",
  loading: "正在加载中...",
  nomore: "没有更多数据了",
};
// 加载状态
const loadingStatus = ref<LoadMoreStatus>("loadmore");
const currentPage = ref(1);

// 查看凭证popup
const payProofPopup = ref<boolean>(false);
const proofImg = ref("");

// modal配置参数
const confirmModal = ref<boolean>(false)
const confirmModalData: ModalDataType = {
  title: '提示',
  content: '确认提货吗？确认后无法取消',
  cancel: {
    text: '取消'
  },
  confirm: {
    text: '提货'
  }
}

function toPaymentInfo(price: number, sellerId: number) {
  navPage("/pages/mine/order/paymentInfo?orderPrice=" + price + "&sellerId=" + sellerId);
}

function toUploadProof(id: number) {
  navPage("/pages/mine/order/uploadProof?id=" + id);
}

function toPutSale(id: number) {
  navPage("/pages/mine/order/putSale?id=" + id);
}

function showProofPopup(img: string){
  payProofPopup.value = true;
  proofImg.value = img;
}

function tabClick(index: any) {
  console.log(index);
  if (index === 0) {
    status.value = "all";
  } else if (index === 1) {
    status.value = "buy";
  } else if (index === 2) {
    status.value = "pay";
  } else if (index === 3) {
    status.value = "confirm";
  } else if (index === 4) {
    status.value = "put-sale";
  }
  //归零数据
  currentPage.value = 1;
  orderList.value = [];
  emptyOrderList.value = false;
  haveData.value = true;
  loadMoreOrder();
}

function cancelOrder() {
  toast({
    title:"请联系客服取消订单",
  })
}

/**
 * 显示确认收款modal 并且绑定当前操作的订单id
 */
function handlePickUp(id: number){
  confirmModal.value = true;
  currentOrderId.value = id;
}

/**
 * 确认收款
 */
 function handleConfirmPickUp() {
  let orderId = currentOrderId.value;
  orderPickUp({ id: orderId }).then((res) => {
    if (res.code === ResultEnum.SUCCESS) {
      toast({
        title: "操作成功",
      });
      // 手动触发 刷新操作
      tabClick(3);
    } else {
      toast({
        title: "系统异常，请重新操作",
      });
    }
  });
}

async function loadMoreOrder() {
  if (!haveData.value) {
    return;
  }
  loadingStatus.value = "loading";
  const { code, result } = await findBuyerOrder({
    current: currentPage.value,
    status: status.value,
  });
  if (code === ResultEnum.SUCCESS) {
    if (result.records.length < 1) {
      //loadingStatus.value = "nomore";
      console.log("没有更多数据了");
      haveData.value = false; // 标记无数据了
      if (currentPage.value === 1) {
        emptyOrderList.value = true;
      }
    }
    orderList.value = orderList.value.concat(result.records);
    currentPage.value++;
  }
  loadingStatus.value = "nomore";
}

onLoad((options: any) => {
  status.value = options.status;
  if (status.value === "all") {
    currentTab.value = 0;
    // 已购买未支付
  } else if (status.value === "buy") {
    currentTab.value = 1;
    // 已支付 未确认
  } else if (status.value === "pay") {
    currentTab.value = 2;
    // 已确认 未上架
  } else if (status.value === "confirm") {
    currentTab.value = 3;
    // 已上架（已完成）
  } else if (status.value === "put-sale") {
    currentTab.value = 4;
  } else {
    currentTab.value = 0;
  }
  //loadMoreOrder();
});

onShow(() => {
  // 刷新数据
  //归零数据
  currentPage.value = 1;
  orderList.value = [];
  emptyOrderList.value = false;
  haveData.value = true;
  loadMoreOrder();
});

// 页面刷到底部
onReachBottom(() => {
  loadMoreOrder();
});
</script>

<style lang="scss" scoped>

.proof-content {
  height: 100%;
  img {
    height: 100%;
    width: 100%;
  }
}
.order-list {
  padding: 20rpx 30rpx;

  &-item {
    background-color: #fff;
    border-radius: 10rpx;
    padding-top: 10rpx;
    padding-bottom: 20rpx;
    margin-top: 20rpx;

    .item-top {
      font-size: 30rpx;
      height: 70rpx;
      display: flex;
      align-items: center;
      padding-left: 20rpx;
      border-bottom: #f1f1f1 3rpx solid;

      .order-status {
        justify-content: flex-end;
        padding-right: 30rpx;
      }
    }

    .item-content {
      height: 150rpx;

      .goods-img {
        //padding: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        img {
          width: 130rpx;
          height: 130rpx;
          border-radius: 5rpx;
        }
      }

      .goods-info {
        display: flex;
        align-items: center;

        .goods-info-other {
          color: #999;
          text-align: end;
          padding-right: 40rpx;
        }
      }
    }

    .item-action {
      //action
      display: flex;
      justify-content: flex-end;
      padding-right: 40rpx;

      .item-button {
        margin-left: 20rpx;
      }
    }
  }
}
</style>
